package controllers

import (
	"Trace/constant"
	"Trace/models"
	"Trace/utils"
	"encoding/json"
	"strconv"

	beego "github.com/beego/beego/v2/server/web"
)

type TraceController struct {
	beego.Controller
}

// TODO Get /getTraceInfoById 根据溯源id获取食品溯源信息
func (Trace *TraceController) GetTraceById() {
	var infos models.TraceInfo
	Id, err := strconv.Atoi(Trace.GetString("Id"))
	if err != nil {
		Trace.Data["json"] = utils.Resp(400, "invalid param", nil)
		Trace.ServeJSON(false)
		return
	}
	body := utils.DoRequest(constant.ContractName, constant.ContractAdress, "getTraceInfo", constant.Abi, constant.ReatilerAdress, []interface{}{Id})
	err = json.Unmarshal(body, &infos)
	if err != nil {
		Trace.Data["json"] = utils.Resp(400, "traceNumber does not exist", nil)
		Trace.ServeJSON(false)
		return
	}
	Trace.Data["json"] = utils.Resp(200, "success", infos)
	Trace.ServeJSON(false)
}

// TODO POST /addTraceInfoByRetailer 零售商添加溯源信息
func (Trace *TraceController) AddTraceInfoByRetailer() {
	var TraceInfoForm models.TraceInfoForm
	err := json.Unmarshal(Trace.Ctx.Input.RequestBody, &TraceInfoForm)
	if err != nil {
		Trace.Data["json"] = utils.Resp(400, "invalid param", nil)
		Trace.ServeJSON(false)
		return
	}
	param := []interface{}{
		TraceInfoForm.TraceNumber,
		TraceInfoForm.TrceName,
		TraceInfoForm.Quality,
	}
	body := utils.DoRequest(constant.ContractName, constant.ContractAdress, "addTraceInfoByDistributor", constant.Abi, constant.DistributorAdress, param)
	if utils.GetJsonVal(string(body), "statusOK") == "true" {
		Trace.Data["json"] = utils.Resp(200, "success", utils.GetJsonVal(string(body), "message"))
		Trace.ServeJSON()
		return
	}
	Trace.Data["json"] = utils.Resp(400, "fail", utils.GetJsonVal(string(body), "message"))
	Trace.ServeJSON()
}

// TODO POST /addTraceInfoByDistributor  分销商添加溯源信息
func (Trace *TraceController) AddTraceInfoByDistributor() {
	var TraceInfoForm models.TraceInfoForm
	err := json.Unmarshal(Trace.Ctx.Input.RequestBody, &TraceInfoForm)
	if err != nil {
		Trace.Data["json"] = utils.Resp(400, "invalid param", nil)
		Trace.ServeJSON(false)
		return
	}
	param := []interface{}{
		TraceInfoForm.TraceNumber,
		TraceInfoForm.TrceName,
		TraceInfoForm.Quality,
	}
	body := utils.DoRequest(constant.ContractName, constant.ContractAdress, "addTraceInfoByDistributor", constant.Abi, constant.DistributorAdress, param)
	if utils.GetJsonVal(string(body), "statusOK") == "true" {
		Trace.Data["json"] = utils.Resp(200, "success", utils.GetJsonVal(string(body), "message"))
		Trace.ServeJSON()
		return
	}
	Trace.Data["json"] = utils.Resp(400, "fail", utils.GetJsonVal(string(body), "message"))
	Trace.ServeJSON()
}
